package com.example.food_contract_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.food_contract_system.domain.*;
import com.example.food_contract_system.mapper.*;
import com.example.food_contract_system.service.OrderService;
import com.example.food_contract_system.util.R;
import com.example.food_contract_system.vo.OrderListVo;
import com.example.food_contract_system.vo.OrderVo;
import com.example.food_contract_system.vo.OrderVoByDistinctVo;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author Lhy
* @description 针对表【order】的数据库操作Service实现
* @createDate 2023-07-06 09:22:15
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService{

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AgencyMapper agencyMapper;
    @Autowired
    private ContractsMapper contractsMapper;
    @Autowired
    private FoodMapper foodMapper;
    @Autowired
    private FreezeMapper freezeMapper;

    @Transactional
    @Override
    public R insertOrder(String aId, String cId, String productList) {
        List<Order> selectOneMyself = orderMapper.selectOneMyself("0",aId);

        Freeze freeze = freezeMapper.selectOne(new QueryWrapper<Freeze>()
                .eq("a_id", aId));
        if (freeze != null){
            return R.error().put("msg", "您的账号已冻结!");
        }

        Agency agency = agencyMapper.selectOne(new QueryWrapper<Agency>()
                .eq("a_id", aId));
        if (agency.getAStatus().equals("0")){
            return R.error(500,"您的账号还在审核中，请等候");
        }
        if (agency.getAStatus().equals("2")){
            return R.error(500,"您的账号未通过审核");
        }
        if (selectOneMyself.size() > 0){
            return R.error(500,"您有未支付的订单!");
        }
        List<OrderVo> orderVos = new ArrayList<>();

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(productList);
            JsonNode regionNode = jsonNode.get("productList");

            if (regionNode.isArray()) {
                Iterator<JsonNode> elements = regionNode.elements();
                while (elements.hasNext()){
                    JsonNode next = elements.next();

                    OrderVo orderVo = new OrderVo();
                    orderVo.setFId(next.get("fid").asInt());
                    orderVo.setONum(next.get("snum").asInt());

                    orderVos.add(orderVo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        UUID uuid = UUID.randomUUID();
        String s = uuid.toString();

        if (orderVos.size()>0){
            List<Order> orderList = orderVos.stream().map(orderVo -> {
                Order order = new Order();

                order.setOId(s.substring(0,4));
                order.setOStatus("0");
                order.setFId(orderVo.getFId());
                order.setONum(orderVo.getONum());

                Date date = new Date();
                // 创建SimpleDateFormat对象，指定日期格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                // 格式化日期
                String formattedDate = sdf.format(date);
                order.setOTime(formattedDate);

                order.setAId(aId);
                order.setCId(cId);

                return order;
            }).collect(Collectors.toList());

            if (orderList.size() > 0){
                orderMapper.insertMyself(orderList);
                shoppingCartMapper.delete(new UpdateWrapper<ShoppingCart>()
                        .eq("a_id", aId));
            }
        }
        return R.ok();
    }

    @Override
    public R getOrderListByUser(String aId) {
        Agency agencyFlag = agencyMapper.selectOne(new QueryWrapper<Agency>()
                .eq("a_id", aId));
        if (agencyFlag.getAParentId().equals("-1")){
            //TODO 这里是给总代理商写的，目的是让总代理商可以看到自己地区的所有经销商的订单列表
            // 根据传进来的总经销商id
        }
        // 封装vo类
        List<OrderVoByDistinctVo> order = orderMapper.selectOneByDistict(aId);
        List<OrderListVo> orderListVos = new ArrayList<>();
        if (order.size() > 0) {

            for (OrderVoByDistinctVo orderVoByDistinctVo : order) {
                OrderListVo orderListVo = new OrderListVo();

                orderListVo.setOStatus(orderVoByDistinctVo.getOStatus());
                orderListVo.setOId(orderVoByDistinctVo.getOId());
                orderListVo.setDate(orderVoByDistinctVo.getOTime());

                orderListVos.add(orderListVo);
            }

            for (OrderListVo orderListVo : orderListVos) {
                Agency agency = agencyMapper.selectOne(new QueryWrapper<Agency>()
                        .eq("a_id", aId));
                if (agency != null) {
                    // 获取经销商的姓名 并封装
                    orderListVo.setAName(agency.getAName());
                }
                List<Order> orderList = orderMapper.selectListByMyself(orderListVo.getOId());
                Contracts contracts = contractsMapper.selectOne(new QueryWrapper<Contracts>()
                        .eq("c_id", orderList.get(0).getCId()));
                if (contracts != null) {
                    orderListVo.setCSrc(contracts.getCSrc());
                    orderListVo.setCName(contracts.getCName());
                }
            }
        }


        return R.ok().put("data", orderListVos);
    }

    @Override
    public R getOrderDetail(String oId) {
        // 根据 oId 获取到该订单的所有信息
        List<Order> orders = orderMapper.selectListByMyself(oId);
        List<ShoppingCart> shoppingCarts = null;
        if (orders.size() > 0) {
            // 遍历 order 根据其中的信息进行封装
            shoppingCarts = orders.stream().map(order -> {
                ShoppingCart shoppingCart = new ShoppingCart();
                shoppingCart.setAId(order.getAId());
                shoppingCart.setFId(order.getFId());

                Food food = foodMapper.selectOne(new QueryWrapper<Food>()
                        .eq("f_id", order.getFId()));

                if (food != null) {
                    shoppingCart.setFNum(food.getFNum());
                    shoppingCart.setFImg(food.getFImg());

                    DecimalFormat df = new DecimalFormat("#.00");
                    String formattedNumber = df.format(food.getFPrice());

                    shoppingCart.setFPrice(formattedNumber);
                    shoppingCart.setFType(food.getFType());
                    shoppingCart.setFName(food.getFName());
                }

                shoppingCart.setDate(order.getOTime());
                shoppingCart.setSNum(order.getONum());

                return shoppingCart;
            }).collect(Collectors.toList());
        }
        return R.ok().put("data", shoppingCarts);
    }

    @Transactional
    @Override
    public R pay(String oId, String aId) {
        Freeze freeze = freezeMapper.selectOne(new QueryWrapper<Freeze>()
                .eq("a_id", aId));
        if (freeze == null){
            //更改订单状态
            int update = orderMapper.updateMyself(oId);
            // 根据订单id获取到所有的商品id
            List<Order> orders = orderMapper.selectListByMyself(oId);
            // 根据id中的商品id进行商品库存的更新
            for (Order order : orders) {
                foodMapper.updateNum(order.getFId(),order.getONum());
            }
        }else{
            return R.error().put("data","您的帐号已冻结");
        }

        return R.ok();
    }

    @Transactional
    @Override
    public R deleteOrder(String oId) {
        orderMapper.deleteMyself(oId);
        return R.ok();
    }
}
